package kinectData.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;

import javax.vecmath.Point3d;

/** 
 * Stores device movement history.
 * 
 * @author Lauren Norrie (norrielm)
*/
public class Device {
	
	private static final int POINT_SAMPLE_SIZE = 5;
	private String id;
	private long lastTrackingTime = 0;
	private Point3d position = new Point3d();
	private ArrayList<Point3d> pointHistory = new ArrayList<Point3d>();
	private int port;
	private String ip;
	
	public Device(Device s){
		this.position = s.position;
		this.lastTrackingTime = s.lastTrackingTime;
		this.id = s.id;
	}
	
	public Device(String ip, int port, String data){
		this.ip = ip;
		this.port = port;
		update(data);
	}
	
	public long getTrackingTime() {
		return lastTrackingTime;
	}

	public String getId() {
		return id;
	}
	
	public Point3d getPosition() {
		return position;
	}
	
	public void update(String data) {
		long currentTime = new Date().getTime();
		StringTokenizer st = new StringTokenizer(data, "#");
		id = st.nextToken();
		double x = Double.parseDouble(st.nextToken());
		double y = Double.parseDouble(st.nextToken());
		double z = Double.parseDouble(st.nextToken());
		Point3d newPosition = new Point3d(x, y, z);
//		updateMovement(newPosition, currentTime);
		position = newPosition;
		lastTrackingTime = currentTime;
	}
	
	public void updateMovement(Point3d newPosition, long currentTime) {
		position = smooth(newPosition);
	}
	
	public Point3d smooth(Point3d newPoint) {
		if (pointHistory.size() > POINT_SAMPLE_SIZE) {
			pointHistory.remove(0);
		}
		pointHistory.add(newPoint);
		
		Point3d average = new Point3d();
		for (Point3d point : pointHistory) {
			average.x += point.x;
			average.y += point.y;
			average.z += point.z;
		}
		average.x /= pointHistory.size();
		average.y /= pointHistory.size();
		average.z /= pointHistory.size();
				
		return average;
	}
	
	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getIp() {
		return ip;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getPort() {
		return port;
	}
	
	public String toString() {
		return String.format("%d#%s#%f#%f#%f", getTrackingTime(), getId(), position.x, position.y, 
			position.z);		
	}
}
